<template>
  <div class="container">
    <el-container class="container1">
      <el-aside width="330px" class="login-aside">
        <el-form
            v-if="!isRegister"
            ref="ruleFormRef"
            class="auth-form"
            :model="ruleForm"
            :rules="rules"
            label-width="50px"
            status-icon
        >
          <el-form-item class="form-item" label="" prop="username">
            <img src="../assets/icon/用户.png" class="input-icon" alt="">
            <input class="underline-input" v-model="ruleForm.username" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item class="form-item" label="" prop="password">
            <img src="../assets/icon/密码.png" class="input-icon" alt="">
            <input class="underline-input" v-model="ruleForm.password" type="password" placeholder="请输入密码"/>
          </el-form-item>
          <div class="role-selector">
            <el-radio-group v-model="radio">
              <el-radio value="1">学生</el-radio>
              <el-radio value="2">管理员</el-radio>
            </el-radio-group>
          </div>
          <div class="remember-me">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          </div>
          <div class="form-footer">
            <el-button @click="login" class="submit-btn">
              登录
            </el-button>
          </div>
          <div @click="toggleRegister" class="toggle-link">没有账号？点我注册</div>
        </el-form>


        <el-form
            v-else
            ref="registerFormRef"
            class="auth-form"
            :model="registerForm"
            :rules="registerRules"
            label-width="50px"
            status-icon
        >
          <el-form-item class="form-item" label="" prop="email">
            <img src="../assets/icon/邮箱.png" class="input-icon" alt="">
            <input class="underline-input" v-model="registerForm.email" placeholder="请输入邮箱"/>
          </el-form-item>
          <el-form-item class="form-item" label="" prop="username">
            <img src="../assets/icon/用户.png" class="input-icon" alt="">
            <input class="underline-input" v-model="registerForm.username" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item class="form-item" label="" prop="password">
            <img src="../assets/icon/密码.png" class="input-icon" alt="">
            <input class="underline-input" v-model="registerForm.password" type="password" placeholder="请输入密码"/>
          </el-form-item>
          <el-form-item class="form-item" label="" prop="verificationCode" style="position: relative;">
            <div class="code-input-wrapper">
              <img src="../assets/icon/验证码.png" class="code-icon" alt="">
              <input class="underline-input" v-model="registerForm.verificationCode" placeholder="请输入验证码"/>
              <el-button
                  size="small"
                  @click="sendVerificationCode"
                  class="code-btn"
                  :disabled="countdown > 0"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
          <div class="form-footer">
            <div @click="toggleRegister" class="toggle-link">已有账号？点我登录</div>
            <el-button @click="registerUser" class="submit-btn">
              注册
            </el-button>
          </div>
        </el-form>
      </el-aside>
      <el-main class="welcome-section">
        <img src="../assets/img/tree.jpg" class="welcome-image">
        <div class="welcome-text">
          欢迎来到
          <span class="brand-name">LearnShare</span>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref, onUnmounted, onMounted} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElLoading } from 'element-plus'
import request from '@/api/request'
import router from "@/router"

const radio = ref('1')
const isRegister = ref(false)
const rememberMe = ref(false)
interface RuleForm {
  username: string
  password: string
}

interface RegisterForm {
  email: string
  username?: string
  password?: string
  verificationCode: string
}

const ruleFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()

const ruleForm = reactive<RuleForm>({
  username: '',
  password: ''
})

const registerForm = reactive<RegisterForm>({
  email: '',
  username: '',
  password: '',
  verificationCode: ''
})

const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '用户名长度为3-15位', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 15, message: '密码长度为3-15位', trigger: 'blur' },
  ],
})

const registerRules = reactive<FormRules<RegisterForm>>({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  username: [
    { min: 3, max: 15, message: '用户名长度为3-15位', trigger: 'blur' },
  ],
  password: [
    { min: 3, max: 15, message: '密码长度为3-15位', trigger: 'blur' },
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})

const login = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '登录中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      // 根据记住密码选择保存或清除账号密码
      if (rememberMe.value) {
        localStorage.setItem('savedUsername', ruleForm.username)
        localStorage.setItem('savedPassword', ruleForm.password)
      } else {
        localStorage.removeItem('savedUsername')
        localStorage.removeItem('savedPassword')
      }
      let param = new FormData()
      param.append('username', ruleForm.username)
      param.append('password', ruleForm.password)

      const url = radio.value === '1' ? '/user/login' : '/admin/login';

      request.post(url, param).then((res: any) => {
        if (res.code === 200) {
          let token = res.data
          localStorage.setItem('token', token)
          window.localStorage.setItem('tokenStartTime', String(new Date().getTime()))

          if (radio.value === '1') {
            localStorage.setItem('userInfo', JSON.stringify(res.data))
          } else {
            localStorage.setItem('adminInfo', JSON.stringify(res.data))
          }
          ElMessage.success(res.message)
          setTimeout(() => {
            radio.value === '1' ? router.push('/') : router.push('/admin/homeAdmin')
          }, 1500)
        } else {
          ElMessage.error(res.message);
        }
      }).catch((error: any) => {
        console.error('请求失败:', error);
        ElMessage.error(error.message || '登录失败');
      }).finally(() => {
        loading.close();
      });
    } else {
      loading.close();
    }
  });
};

const countdown = ref(0)
let timer: number | null = null

const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0 && timer) {
      clearInterval(timer)
      timer = null
    }
  }, 1000)
}

const sendVerificationCode = () => {
  if (!registerForm.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }

  if (countdown.value > 0) {
    ElMessage.warning(`请等待${countdown.value}秒后再试`)
    return
  }

  request.get(`/user/verificationCode?email=${encodeURIComponent(registerForm.email)}`)
    .then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('验证码已发送')
        startCountdown()
      } else {
        ElMessage.error(res.message)
      }
    })
    .catch((error: any) => {
      console.error('发送验证码失败:', error)
      ElMessage.error('发送验证码失败')
    })
}

const registerUser = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '注册中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  registerFormRef.value?.validate((valid) => {
    if (valid) {
      const param = {
        email: registerForm.email,
        username: registerForm.username,
        password: registerForm.password,
        verificationCode: registerForm.verificationCode
      }

      request.post('/user/register', param).then((res: any) => {
        if (res.code === 200) {
          ElMessage.success(res.message)
          isRegister.value = false
        } else {
          ElMessage.error(res.message);
        }
      }).catch((error: any) => {
        console.error('请求失败:', error);
        ElMessage.error(error.message || '注册失败');
      }).finally(() => {
        loading.close();
      });
    } else {
      loading.close();
    }
  });
};

const toggleRegister = () => {
  isRegister.value = !isRegister.value
};

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
onMounted(() => {
  const savedUsername = localStorage.getItem('savedUsername')
  const savedPassword = localStorage.getItem('savedPassword')
  if (savedUsername && savedPassword) {
    ruleForm.username = savedUsername
    ruleForm.password = savedPassword
    rememberMe.value = true
  }
})
</script>

<style scoped>
.container {
  display: grid;
  place-items: center;
  height: 100vh;
  background-image: url('../assets/img/login.jpg');
  background-size: cover;
  background-position: center;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.container1 {
  height: 450px;
  width: 750px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.container1:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
}

.login-aside {
  background-color: #f8f9fa;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 表单容器样式优化 */
.auth-form {
  width: 380px;
  padding: 30px;
  background-color: white;
  border-radius: 12px;
  margin-left: 10px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}

/* 表单项样式优化 */
.form-item {
  margin-bottom: 25px;
  position: relative;
  border-bottom: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.form-item:hover {
  border-bottom-color: #67c23a;
}

/* 输入框图标样式优化 */
.input-icon {
  width: 18px;
  margin-right: 12px;
  opacity: 0.8;
  transition: all 0.3s;
}

/* 输入框样式优化 */
.underline-input {
  border: none;
  background: transparent;
  outline: none;
  padding: 10px 0;
  width: 100%;
  font-size: 14px;
  color: #333;
  transition: all 0.3s;
}

.underline-input::placeholder {
  color: #b0b0b0;
  font-size: 13px;
}

.underline-input:focus {
  border-bottom-color: #67c23a;
}

/* 角色选择器样式优化 */
.role-selector {
  margin: 25px 0;
  text-align: center;
}

.el-radio {
  margin: 0 10px;
}

/* 登录按钮样式优化 */
.submit-btn {
  width: 100%;
  padding: 12px;
  font-size: 14px;
  letter-spacing: 1px;
  border-radius: 6px !important;
  background: linear-gradient(135deg, #67c23a, #5daf34) !important;
  box-shadow: 0 4px 6px rgba(103, 194, 58, 0.2) !important;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 10px rgba(103, 194, 58, 0.3) !important;
}

/* 切换链接样式优化 */
.toggle-link {
  display: block;
  text-align: center;
  margin-top: 20px;
  font-size: 13px;
  color: #67c23a;
  cursor: pointer;
  transition: all 0.2s;
}

.toggle-link:hover {
  color: #5daf34;
  text-decoration: underline;
}

.form-item:hover {
  border-bottom-color: #67c23a;
}

.input-icon {
  width: 20px;
  margin-right: 10px;
  opacity: 0.7;
}

.underline-input {
  border: none;
  background-color: transparent;
  outline: none;
  padding: 8px 0;
  width: 100%;
  font-size: 14px;
  color: #333;
}

.underline-input::placeholder {
  color: #aaa;
}

.underline-input:focus {
  border-bottom-color: #67c23a;
}

.role-selector {
  margin: 20px 0;
  text-align: center;
}

.el-radio {
  margin-right: 15px;
}

.el-radio__input.is-checked+.el-radio__label {
  color: #67c23a !important;
}

.el-radio__inner {
  border-color: #c0c4cc;
}

.el-radio__input.is-checked .el-radio__inner {
  background-color: #67c23a;
  border-color: #67c23a;
}

.form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
}

.submit-btn {
  color: white !important;
  background-color: #67c23a !important;
  border-radius: 20px !important;
  border: none !important;
  padding: 10px 25px;
  transition: all 0.3s;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.submit-btn:hover {
  background-color: #5daf34 !important;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.toggle-link {
  color: #67c23a;
  cursor: pointer;
  font-size: 13px;
  margin-top: 15px;
  text-align: center;
  transition: all 0.2s;
}

.toggle-link:hover {
  color: #5daf34;
  text-decoration: underline;
}

.code-input-wrapper {
  display: flex;
  align-items: center;
}

.code-icon {
  width: 20px;
  margin-right: 10px;
  opacity: 0.7;
}

.code-btn {
  margin-left: 10px;
  background-color: #f0f2f5 !important;
  color: #67c23a !important;
  border: none !important;
}

.code-btn:hover {
  background-color: #e6e8eb !important;
}

.welcome-section {
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.welcome-image {
  width: 320px;
  margin-bottom: 20px;
  border-radius: 8px;
}

.welcome-text {
  font-size: 22px;
  color: #333;
  line-height: 1.6;
}

.brand-name {
  font-size: 32px;
  font-weight: bold;
  color: #67c23a;
  font-family: '华文行楷', cursive;
}
.remember-me {
  margin: -15px 0;
  text-align: left;
}

.remember-me .el-checkbox {
  color: #666;
  font-size: 13px;
}
</style>
